﻿function _submitLive() {
    var sb = [];
    sb.push('odds-display/today-data.aspx?od-param=');
    sb.push($M('odds-display').getOddsDisplayParam());
    sb.push('&fi=0&v=');
    sb.push(_syn.liveVersion);
    sb.push($M('more').getMoreParam(true));
    return TiLib.Ajax.sendRequest('today-double-live', sb.join(''));
}

function _submitNonlive() {
    var sb = [];
    sb.push('odds-display/today-data.aspx?od-param=');
    sb.push($M('odds-display').getOddsDisplayParam());
    sb.push('&fi=1&v=');
    sb.push(_syn.nonliveVersion);
    sb.push('&dl=');
    sb.push($M('odds-display').getDisplaySetting('daylight-type'));
    sb.push($M('more').getMoreParam(false));
    return TiLib.Ajax.sendRequest('today-double-nonlive', sb.join(''));
}

//od-param - 显示参数 序列：'token', 'sport', 'market-page', 'price-style', 'sorting', 'market-showing', 'odds-mode', 'event-date','daylight-type'  默认：1,1,1,1,1,2,1,2,1
//v - 版本号，返回结果中保存
//fi - 是否是滚球， 0 滚球 1 非直播中
//dl - 非直播 daylight-type 3=全部 2=23点之后 1=23前之前

function _populateLiveSection(d) {
    $M('odds-display').clearRef();
    var template = _templateLive;
    var favTemplate = _templateFavourite;
    var cache = _liveCache;
    var favCache = $M('favourite').getCache();
    var usesLocalTime = $M('odds-display').getDisplaySetting('display-in-local-time');
    var tagEventResults = cache.getTagEventResultArray();
    var c = tagEventResults.length;
    var rows = [];
    var oddsRowIndex = 0;
    var templateRowIndex = 0;
    var tournamentId = 0;
    var marketGroupId = 0;
    var favourite;
    var showMarketGroups = $M('odds-display').getDisplaySetting('market-showing') == 2 ? true : false;
    var selectedOddId = $M('ticket').getOddIdOption();
    d['market-page'] = template['market-page-today'].getText();
    d['live-ext'] = template['live-ext'].getText();
    d['sport-id'] = $M('odds-display').getDisplaySetting('sport');
    d['sport'] = TiLib.Text.encodeHTML(cache.getSportName());
    for (var i = 0; i < c; ++i) {
        var tagEventResult = tagEventResults[i];
        var tournament = tagEventResult[1];
        var event = tagEventResult[2];
        var eventId = event[0];
        var eventResult = tagEventResult[3];
        var eventResultId = eventResult[0];
        var eventResultExtra = tagEventResult[4];
        var oddsByMarketDisplayId = tagEventResult[5];
        var marketGroup = tagEventResult[6];
        if (marketGroup && marketGroup[0] != 0 && !showMarketGroups) {
            continue;
        }
        var oddsFTime1X2 = oddsByMarketDisplayId ? oddsByMarketDisplayId[_MarketDisplay.FTime1X2] : null;
        var oddsFHalf1X2 = oddsByMarketDisplayId ? oddsByMarketDisplayId[_MarketDisplay.FHalf1X2] : null;
        var oddsFTimeHDP = oddsByMarketDisplayId ? oddsByMarketDisplayId[_MarketDisplay.FTimeHDP] : null;
        var oddsFHalfHDP = oddsByMarketDisplayId ? oddsByMarketDisplayId[_MarketDisplay.FHalfHDP] : null;
        var oddsFTimeOU = oddsByMarketDisplayId ? oddsByMarketDisplayId[_MarketDisplay.FTimeOU] : null;
        var oddsFHalfOU = oddsByMarketDisplayId ? oddsByMarketDisplayId[_MarketDisplay.FHalfOU] : null;
        var oddsFTimeLS = oddsByMarketDisplayId ? oddsByMarketDisplayId[_MarketDisplay.FTimeLS] : null;
        var rowCount = 0;
        if (oddsFTime1X2 && rowCount < oddsFTime1X2.length) {
            rowCount = oddsFTime1X2.length;
        }
        if (oddsFHalf1X2 && rowCount < oddsFHalf1X2.length) {
            rowCount = oddsFHalf1X2.length;
        }
        if (oddsFTimeHDP && rowCount < oddsFTimeHDP.length) {
            rowCount = oddsFTimeHDP.length;
        }
        if (oddsFHalfHDP && rowCount < oddsFHalfHDP.length) {
            rowCount = oddsFHalfHDP.length;
        }
        if (oddsFTimeOU && rowCount < oddsFTimeOU.length) {
            rowCount = oddsFTimeOU.length;
        }
        if (oddsFHalfOU && rowCount < oddsFHalfOU.length) {
            rowCount = oddsFHalfOU.length;
        }
        if (oddsFTimeLS && rowCount < oddsFTimeLS.length) {
            rowCount = oddsFTimeLS.length;
        }
        if (rowCount == 0 && eventResultExtra && rowCount < eventResultExtra[1]) {
            var frozenOdds = eventResultExtra[8];
            var count = null;
            if (frozenOdds) {
                count = isNaN(frozenOdds[_MarketDisplay.FTimeHDP]) ? 0 : frozenOdds[_MarketDisplay.FTimeHDP];
                rowCount = Math.max(rowCount, count);
                count = isNaN(frozenOdds[_MarketDisplay.FHalfHDP]) ? 0 : frozenOdds[_MarketDisplay.FHalfHDP];
                rowCount = Math.max(rowCount, count);
                count = isNaN(frozenOdds[_MarketDisplay.FTimeOU]) ? 0 : frozenOdds[_MarketDisplay.FTimeOU];
                rowCount = Math.max(rowCount, count);
                count = isNaN(frozenOdds[_MarketDisplay.FHalfOU]) ? 0 : frozenOdds[_MarketDisplay.FHalfOU];
                rowCount = Math.max(rowCount, count);
                count = isNaN(frozenOdds[_MarketDisplay.FTime1X2]) ? 0 : frozenOdds[_MarketDisplay.FTime1X2];
                rowCount = Math.max(rowCount, count);
                count = isNaN(frozenOdds[_MarketDisplay.FHalf1X2]) ? 0 : frozenOdds[_MarketDisplay.FHalf1X2];
                rowCount = Math.max(rowCount, count);
                count = isNaN(frozenOdds[_MarketDisplay.FTimeLS]) ? 0 : frozenOdds[_MarketDisplay.FTimeLS];
                rowCount = Math.max(rowCount, count);
                rowCount = rowCount > 1 ? 1 : rowCount;
            }
        }
        if (rowCount <= 0) {
            continue;
        }
        if (tournamentId != tournament[0]) {
            OddsUtility.populateTournament(d, tournament);
            OddsUtility.populateTournamentInfo(d, tournament, template['tournament-info']);
            if (favCache.hasTournament(tournament[0])) {
                favourite = 'icon-live-tournament-remove';
            } else {
                favourite = 'icon-live-tournament-add';
            }
            d['icon-favourite-tournament'] = favTemplate[favourite].getText(d);
            rows.push(template['row-tournament'].getText(d));
            tournamentId = tournament[0];
            marketGroupId = 0;
        }
        OddsUtility.populateEvent(d, event);
        d['icon-video'] = _mediaCache.hasLiveVideo(eventId) ? template['icon-video'].getText(d) : null;
        d['ls-class'] = '';
        d['ls-tooltip'] = '';
        d['ls-id'] = 0;
        if (_mediaCache.hasLiveCenter(eventId)) {
            d['ls-class'] = 'ls-time-column';
            d['ls-tooltip'] = template['ls-tooltip'].getText();
            d['ls-id'] = d['event-id'];
        }
        d['event-result-id'] = eventResultId;
        d['icon-statistics'] = '';
        if (event[8]) {
            d['icon-statistics'] = template['icon-statistics'].getText(d);
        }
        d['home-score'] = eventResult[3];
        d['away-score'] = eventResult[4];
        d['score-separator'] = template['score-separator'].getText(d);
        d['draw'] = template['draw'].getText();
        d['vs'] = template['vs'].getText();
        d['score-class'] = cache.isScoreChanged(eventResultId) ? 'score-change' : '';
        var moreContent = '';
        d['more-opened'] = '';
        d['more-icon-hover'] = '';
        if ($M('more').isMoreOpened(eventResultId, 0)) {
            moreContent = $M('more').getContent(11);
        } else if ($M('more').isClosing(eventResultId, 0)) {
            moreContent = $M('more').getClosingContent();
        }
        if (moreContent) {
            d['more-opened'] = 'more-opened';
            d['more-icon-hover'] = 'more-icon-hover';
        }
        d['odds-count'] = showMarketGroups ? cache.getEventResultMoreOddsCount(eventResultId) : cache.getEventMoreOddsCount(eventResultId);
        d['icon-more'] = d['odds-count'] ? template['icon-more'].getText(d) : '';
        if (marketGroup && marketGroup[0]) {
            OddsUtility.populateMarketGroup(d, marketGroup);
            OddsUtility.populateMarketGroupTeams(d, marketGroup);
            if (marketGroupId != marketGroup[0]) {
                marketGroupId = marketGroup[0];
                rows.push(template['row-market-group'].getText(d));
            }
            d['icon-statistics'] = '';
            d['icon-video'] = '';
        } else {
            marketGroupId = 0;
        }
        if (favCache.hasEventResult(eventResultId) || favCache.hasTournament(tournamentId)) {
            favourite = 'icon-live-event-remove';
        } else {
            favourite = 'icon-live-event-add';
        }
        d['icon-favourite-event'] = favTemplate[favourite].getText(d);
        d['live-time'] = template['time-live'].getText(d);
        if (eventResultExtra) {
            var period = eventResultExtra[2];
            if (period > 0) {
                if (period == 5) {
                    d['live-time'] = template['time-halftime'].getText(d);
                } else {
                    d['live-time'] = OddsUtility.getLiveTime(period, cache.getLiveStartTime(eventResultId), eventResultExtra[3], eventResultExtra[4]);
                    var injuryTime = parseInt('' + eventResultExtra[7], 10);
                    if (injuryTime && injuryTime > 0) {
                        d['injuryTimeCount'] = injuryTime;
                        d['live-time'] += template['injury-time'].getText(d);
                    }
                }
            }
        }
        var homeRedCards = '';
        var awayRedCards = '';
        if (eventResultExtra) {
            var redCardIndex;
            var redCardCount = eventResultExtra[5];
            if (redCardCount) {
                for (redCardIndex = 0; redCardIndex < redCardCount; ++redCardIndex) {
                    homeRedCards += template['red-card'].getText(d);
                }
            }
            redCardCount = eventResultExtra[6];
            if (redCardCount) {
                for (redCardIndex = 0; redCardIndex < redCardCount; ++redCardIndex) {
                    awayRedCards += template['red-card'].getText(d);
                }
            }
        }
        d['home-red-cards'] = homeRedCards;
        d['away-red-cards'] = awayRedCards;
        d['sub-row'] = '';
        for (var rowIndex = 0; rowIndex < rowCount; ++rowIndex) {
            var odds;
            var has1X2 = false;
            var hdp = 0;
            odds = oddsFTimeHDP ? oddsFTimeHDP[rowIndex] : null;
            if (odds) {
                hdp = odds[1][4];
            }
            odds = oddsFHalfHDP ? oddsFHalfHDP[rowIndex] : null;
            if (odds && !hdp) {
                hdp = odds[1][4];
            }
            d['hdp-type'] = hdp ? (hdp > 0 ? 1 : 2) : 0;
            d['home-color-class'] = hdp > 0 ? 'Red' : 'Blue';
            d['away-color-class'] = hdp < 0 ? 'Red' : 'Blue';
            odds = oddsFTime1X2 ? oddsFTime1X2[rowIndex] : null;
            if (odds) {
                has1X2 = true;
                OddsUtility.populateOdds(d, odds, template['price-text'], cache.getPriceAdjustIndicators(odds[0]), null, null, selectedOddId);
                OddsUtility.populateOddsIndicators(d, odds, cache.getPriceAdjustIndicators(odds[0]), 'price-up', 'price-down');
            } else {
                OddsUtility.clearOdds(d, _MarketDisplay.FTime1X2);
                OddsUtility.clearOddsIndicators(d, _MarketDisplay.FTime1X2);
            }
            odds = oddsFHalf1X2 ? oddsFHalf1X2[rowIndex] : null;
            if (odds) {
                has1X2 = true;
                OddsUtility.populateOdds(d, odds, template['price-text'], cache.getPriceAdjustIndicators(odds[0]), null, null, selectedOddId);
                OddsUtility.populateOddsIndicators(d, odds, cache.getPriceAdjustIndicators(odds[0]), 'price-up', 'price-down');
            } else {
                OddsUtility.clearOdds(d, _MarketDisplay.FHalf1X2);
                OddsUtility.clearOddsIndicators(d, _MarketDisplay.FHalf1X2);
            }
            odds = oddsFTimeLS ? oddsFTimeLS[rowIndex] : null;
            if (odds) {
                has1X2 = true;
                OddsUtility.populateOdds(d, odds, template['price-text'], cache.getPriceAdjustIndicators(odds[0]), null, null, selectedOddId);
                OddsUtility.populateOddsIndicators(d, odds, cache.getPriceAdjustIndicators(odds[0]), 'price-up', 'price-down');
            } else {
                OddsUtility.clearOdds(d, _MarketDisplay.FTimeLS);
                OddsUtility.clearOddsIndicators(d, _MarketDisplay.FTimeLS);
            }
            odds = oddsFTimeHDP ? oddsFTimeHDP[rowIndex] : null;
            if (odds) {
                OddsUtility.populateOdds(d, odds, template['price-text'], cache.getPriceAdjustIndicators(odds[0]), null, null, selectedOddId);
                OddsUtility.populateOddsPoints(d, odds);
                OddsUtility.populateOddsIndicators(d, odds, cache.getPriceAdjustIndicators(odds[0]), 'price-up', 'price-down');
            } else {
                OddsUtility.clearOdds(d, _MarketDisplay.FTimeHDP);
                OddsUtility.clearOddsPoints(d, _MarketDisplay.FTimeHDP);
                OddsUtility.clearOddsIndicators(d, _MarketDisplay.FTimeHDP);
            }
            odds = oddsFHalfHDP ? oddsFHalfHDP[rowIndex] : null;
            if (odds) {
                OddsUtility.populateOdds(d, odds, template['price-text'], cache.getPriceAdjustIndicators(odds[0]), null, null, selectedOddId);
                OddsUtility.populateOddsPoints(d, odds);
                OddsUtility.populateOddsIndicators(d, odds, cache.getPriceAdjustIndicators(odds[0]), 'price-up', 'price-down');
            } else {
                OddsUtility.clearOdds(d, _MarketDisplay.FHalfHDP);
                OddsUtility.clearOddsPoints(d, _MarketDisplay.FHalfHDP);
                OddsUtility.clearOddsIndicators(d, _MarketDisplay.FHalfHDP);
            }
            odds = oddsFTimeOU ? oddsFTimeOU[rowIndex] : null;
            if (odds) {
                OddsUtility.populateOdds(d, odds, template['price-text'], cache.getPriceAdjustIndicators(odds[0]), null, null, selectedOddId);
                OddsUtility.populateOddsPoints(d, odds);
                OddsUtility.populateOddsLabels(d, odds);
                OddsUtility.populateOddsIndicators(d, odds, cache.getPriceAdjustIndicators(odds[0]), 'price-up', 'price-down');
            } else {
                OddsUtility.clearOdds(d, _MarketDisplay.FTimeOU);
                OddsUtility.clearOddsPoints(d, _MarketDisplay.FTimeOU);
                OddsUtility.clearOddsLabels(d, _MarketDisplay.FTimeOU);
                OddsUtility.clearOddsIndicators(d, _MarketDisplay.FTimeOU);
            }
            odds = oddsFHalfOU ? oddsFHalfOU[rowIndex] : null;
            if (odds) {
                OddsUtility.populateOdds(d, odds, template['price-text'], cache.getPriceAdjustIndicators(odds[0]), null, null, selectedOddId);
                OddsUtility.populateOddsPoints(d, odds);
                OddsUtility.populateOddsLabels(d, odds);
                OddsUtility.populateOddsIndicators(d, odds, cache.getPriceAdjustIndicators(odds[0]), 'price-up', 'price-down');
            } else {
                OddsUtility.clearOdds(d, _MarketDisplay.FHalfOU);
                OddsUtility.clearOddsPoints(d, _MarketDisplay.FHalfOU);
                OddsUtility.clearOddsLabels(d, _MarketDisplay.FHalfOU);
                OddsUtility.clearOddsIndicators(d, _MarketDisplay.FHalfOU);
            }
            d['row-index'] = oddsRowIndex;
            var rowTemplateName;
            if (marketGroup && marketGroup[5]) {
                rowTemplateName = 'row-event-yesno';
                if (has1X2) {
                    rowTemplateName = 'row-event-yesno-1x2';
                }
            } else if (!has1X2 && template['row-event-no1x2']) {
                rowTemplateName = 'row-event-no1x2';
            } else {
                rowTemplateName = 'row-event';
            }
            d['bg-color'] = (templateRowIndex & 1) ? '#FFDDCC' : '#FFDDCC';
            rows.push(template[rowTemplateName].getText(d));
            oddsRowIndex++;
            d['icon-statistics'] = null;
            d['icon-video'] = null;
            d['ls-class'] = '';
            d['ls-id'] = 0;
            d['ls-tooltip'] = '';
            d['home-score'] = null;
            d['away-score'] = null;
            d['score-separator'] = null;
            d['draw'] = null;
            d['vs'] = null;
            d['score-class'] = null;
            d['icon-more'] = null;
            d['live-time'] = null;
            d['home-red-cards'] = null;
            d['away-red-cards'] = null;
            d['original-home'] = null;
            d['original-away'] = null;
            d['home'] = null;
            d['away'] = null;
            d['tv-channel'] = null;
            d['sub-row'] = 'subrow';
            d['icon-favourite-event'] = null;
        }
        rows.push(moreContent);
        templateRowIndex++;
    }
    var ret = 0;
    if (rows.length > 0) {
        d['rows'] = rows.join('');
        d['refresh-count'] = _syn.liveRefreshCount;
        d['refresh-button'] = _syn.liveCooldownCount ? template['refresh-refreshing'].getText() : template['refresh-countdown'].getText(d);
        d['additional-class'] = _getAdditionalClass();
        d['table'] = template['table'].getText(d);
        d['odds-display-live'] = template['odds-display-live'].getText(d);
        ret = rows.length;
    } else if (_syn.liveVersion == 0 && _liveCache.isEmpty()) {
        _drawLoading();
        ret = 0;
    } else {
        d['odds-display-live'] = '';
        ret = 0;
    }
    return ret;
}

function __Module_OddsDisplay(oddsDisplayParam, displayInLocalTime, oddsDisplayInitialParams, daylightTypePeriod) {
    var _self = this;
    var _submodule = null;
    var _displayInLocalTime = displayInLocalTime;
    var _daylightType = 0;
    var _daylightTypePeriod = daylightTypePeriod;
    var _oddsDisplayInitialParams = oddsDisplayInitialParams;
    var _oddsDisplayParam = oddsDisplayParam;
    this.getOddsDisplayParam = function () {
        return _oddsDisplayParam.getJoinedValues();
    }
    var _show1X2DC = 1;
    var _showFTCS = 1;
    var _limitedRows = 50;
    var _lastExtended = new Date();
    var _additionalRows = 50;
    this.initiate = function () {
        TiLib.Timer.addToSecondTimer(_self);
        _replaceSubmodule();
    };
    this.onTemplate = function (name, extension) {
        if (_submodule && _submodule.onTemplate) {
            _submodule.onTemplate(name, extension);
        }
    };
    this.onIdle = function (token, data) {
        if (token == _oddsDisplayParam.getValue('token')) {
            if (_submodule && _submodule.onIdle) {
                _submodule.onIdle(data);
            }
        }
    };
    this.onUpdate = function (token, data) {
        if (token == _oddsDisplayParam.getValue('token')) {
            if (_submodule && _submodule.onUpdate) {
                _submodule.onUpdate(data);
            }
        }
    }
    this.onUpdateFavourite = function (token, data) {
        if (token == _oddsDisplayParam.getValue('token')) {
            if (_submodule && _submodule.onUpdateFavourite) {
                _submodule.onUpdateFavourite(data);
            }
        }
    }
    this.onChangeDisplaySetting = function (token, key, value) {
        if (token == _oddsDisplayParam.getValue('token')) {
            _oddsDisplayParam.setValue(key, value);
        }
    };
    this.extend = function () {
        var now = new Date();
        var enabled = _oddsDisplayInitialParams['limitedDisplayEnabled'];
        if (enabled) {
            if (now - _lastExtended >= 200 && _limitedRows < Number.MAX_VALUE) {
                _limitedRows += _additionalRows;
                if (_submodule && _submodule.draw) {
                    _submodule.draw();
                }
                _lastExtended = new Date();
            }
        }
    }
    this.onTime = function () {
        if (_submodule && _submodule.onTime) {
            _submodule.onTime();
        }
    };
    var _hadReloaded = false;
    this.onReload = function () {
        if (!_hadReloaded) {
            _hadReloaded = true;
            var minutes = Math.random() * 300;
            setTimeout(function () {
                document.location.replace(document.location.href);
            }, minutes * 1000);
        }
    };
    this.onSettingChanged = function () {
        var needsReplaceModule = false;
        var needsRefresh = false;
        var needsDraw = false;
        var names = CookieHelper.getNames('od-param-');
        var c = names.length;
        for (var i = 0; i < c; ++i) {
            var value = CookieHelper.getValue(names[i]);
            if (value && value !== null) {
                var key = names[i].substring('od-param-'.length);
                switch (key) {
                    case 'display-in-local-time':
                        _displayInLocalTime = value;
                        needsDraw = true;
                        break;
                    case 'odds-mode':
                        _increaseToken();
                        _oddsDisplayParam.setValue(key, value);
                        needsReplaceModule = true;
                        break;
                    case 'price-style':
                        _increaseToken();
                        _oddsDisplayParam.setValue(key, value);
                        needsRefresh = true;
                        break;
                    case 'sorting':
                    case 'market-showing':
                        _oddsDisplayParam.setValue(key, value);
                        needsDraw = true;
                        break;
                }
            }
        }
        if (needsReplaceModule) {
            _replaceSubmodule();
        } else if (needsRefresh) {
            if (_submodule && _submodule.refresh) {
                _submodule.refresh(true);
            }
        } else if (needsDraw) {
            if (_submodule && _submodule.draw) {
                _submodule.draw();
            }
        }
    };
    this.onClick = function (event) {
        if (!event) event = window.event;
        if (_submodule && _submodule.onClick && !_submodule.onClick(event)) {
            event.returnValue = false;
            return false;
        }
        if (!_onClick(event)) {
            event.returnValue = false;
            return false;
        }
        return true;
    };

    function _onClick(event) {
        var e = event.srcElement ? event.srcElement : event.target;
        while (e) {
            var id = e.id;
            var element = e;
            e = e.parentNode;
            if (!id) continue;
            if (id == 'bu:void') return false;
            var atom = id.split(':');
            var count = atom.length;
            if (count >= 3 && atom[0] == 'bu' && atom[1] == 'od') {
                switch (atom[2]) {
                    case 'refresh':
                        _self.refresh();
                        return false;
                    case 'refresh-live':
                        _self.refreshLive();
                        return false;
                    case 'refresh-nonlive':
                        _self.refreshNonlive();
                        return false;
                    case 'select-tournament':
                        if (count >= 4) {
                            $M('select-tournament').open(atom[3]);
                        }
                        return false;
                    case 'statistics':
                        if (count >= 4) {
                            OddsUtility.openStatistics(atom[3]);
                            if ($M('global') && $M('global').incGA) {
                                $M('global').incGA('statistics', 'center');
                            }
                        }
                        return false;
                    case 'price':
                        if (count >= 6) {
                            var oddsSource = _getOddsSource(e);
                            _openTicket(atom[3], atom[4], atom[5], atom[6], "s", false, oddsSource, element, id);
                        }
                        return false;
                    case 'mpprice':
                        if (count >= 6) {
                            var oddsSource = _getOddsSource(e);
                            _openTicket(atom[3], atom[4], atom[5], atom[6], "mp", false, oddsSource, element, id);
                        }
                        return false;
                    case 'orprice-live':
                        if (count >= 6) {
                            _openTicket(atom[3], atom[4], atom[5], atom[6], "or", true, null, element, id);
                        }
                        return false;
                    case 'orprice-nonlive':
                        if (count >= 6) {
                            _openTicket(atom[3], atom[4], atom[5], atom[6], "or", false, null, element, id);
                        }
                        return false;
                    case 'sorting':
                        if (count >= 4) {
                            _self.setDisplaySetting('sorting', parseInt(atom[3]));
                        }
                        return false;
                    case 'market-showing':
                        if (count >= 4) {
                            _self.setDisplaySetting('market-showing', parseInt(atom[3]));
                        }
                        return false;
                    case 'price-style':
                        if (count >= 4) {
                            _self.setDisplaySetting('price-style', parseInt(atom[3]));
                        }
                        return false;
                    case 'odds-mode':
                        if (count >= 4) {
                            _self.setDisplaySetting('odds-mode', parseInt(atom[3]));
                        }
                        return false;
                    case 'event-date':
                        if (count >= 4) {
                            _self.setDisplaySetting('event-date', parseInt(atom[3]));
                        }
                        return false;
                    case '1x2dc':
                        if (count >= 4) {
                            _self.setDisplaySetting('1x2dc', parseInt(atom[3]));
                        }
                        return false;
                    case 'csft':
                        if (count >= 4) {
                            _self.setDisplaySetting('csft', parseInt(atom[3]));
                        }
                        return false;
                    case 'live-more':
                        if (count >= 4) {
                            var eventResultId = parseInt(atom[3]);
                            element.className = TiLib.Text.addClassItem(element.className, 'more-loading');
                            if ($M('more').isMoreOpened(eventResultId, 0)) {
                                $M('more').closeMoreBlock();
                            } else {
                                $M('more').openMoreBlock(eventResultId, 0, _getMarketFrameId(true));
                            }
                            if ($M('global') && $M('global').incGA) {
                                $M('global').incGA('live-more', 'center');
                            }
                        }
                        return false;
                    case 'nonlive-more':
                        if (count >= 4) {
                            var eventResultId = parseInt(atom[3]);
                            element.className = TiLib.Text.addClassItem(element.className, 'more-loading');
                            if ($M('more').isMoreOpened(eventResultId, 1)) {
                                $M('more').closeMoreBlock();
                            } else {
                                $M('more').openMoreBlock(eventResultId, 1, _getMarketFrameId(false));
                            }
                            if ($M('global') && $M('global').incGA) {
                                $M('global').incGA('nonlive-more', 'center');
                            }
                        }
                        return false;
                    case 'video':
                        if (count >= 4) {
                            $M('top-banner').onSBOBETvClick(atom[3], 'center');
                        }
                        return false;
                    case 'daylight-type':
                        if (count >= 4) {
                            _self.setDisplaySetting('daylight-type', parseInt(atom[3]));
                        }
                        return false;
                    case 'ls':
                        if (count >= 4) {
                            var eventId = atom[3];
                            if (eventId && parseInt(eventId) > 0) {
                                var sportId = _oddsDisplayParam.getValue('sport');
                                CookieHelper.setValue('opened-event-id', parseInt(atom[3]));
                                CookieHelper.setValue('opened-sport-id', sportId);
                                if ($M('global') && $M('global').incGA) {
                                    $M('global').incGA('lives-fire', 'center');
                                }
                                if ($M('top-banner') && $M('top-banner').goProduct) {
                                    $M('top-banner').goProduct('livesports');
                                } else {
                                    var host = document.location.host;
                                    var dest = '/web-root/restricted/live-sport/live-sport.aspx';
                                    var query = document.location.search;
                                    document.location.href = 'http://' + host + dest + query;
                                }
                            }
                        }
                        return false;
                }
            }
        }
        return true;
    }
    this.onMouseOver = function (event, id) {
        if (_submodule && _submodule.onMouseOver && !_submodule.onMouseOver(event, id)) {
            event.returnValue = false;
            return false;
        }
    };
    this.onMouseOut = function (event, id) {
        if (_submodule && _submodule.onMouseOut && !_submodule.onMouseOut(event, id)) {
            event.returnValue = false;
            return false;
        }
    };
    var _selectedElements = {};
    var _refNodes = {};
    var _refDummyClassName = {};
    var _firstOpen = false;

    function getElementsByClassName(className, tag, elm) {
        var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
        var tag = tag || "*";
        var elm = elm || document;
        var elements = (tag == "*" && elm.all) ? elm.all : elm.getElementsByTagName(tag);
        var returnElements = [];
        var current;
        var length = elements.length;
        for (var i = 0; i < length; i++) {
            current = elements[i];
            if (testClass.test(current.className)) {
                returnElements.push(current);
            }
        }
        return returnElements;
    }

    function _openTicket(oddsId, option, price, hdpType, betType, isLiveOutright, oddsSource, srcElement, id) {
        if (!_firstOpen) {
            var elements = null;
            if (document.getElementsByClassName) {
                elements = document.getElementsByClassName('odds-selected');
            } else {
                elements = getElementsByClassName('odds-selected');
            }
            var selectedOddsElement = [];
            for (var i = 0; i < elements.length; i++) {
                selectedOddsElement.push(elements[i]);
            }
            for (var i = 0; i < selectedOddsElement.length; i++) {
                var node = selectedOddsElement[i];
                var className = node.className;
                var dummyClass = 'dummy-class';
                while (node) {
                    if (node.id) {
                        var ids = node.id.split(':');
                        if (ids[2] == 'price' || ids[2] == 'mpprice') {
                            dummyClass = 'dummy-more-class';
                            break;
                        }
                    }
                    node = node.parentNode;
                }
                selectedOddsElement[i].className = className.replace('odds-selected', dummyClass);
            }
            _firstOpen = true;
            $M('ticket').setDisabledGetOddsIdOption(true);
        }
        switch (betType) {
            case "or":
                $M('ticket').openTicket(oddsId, option, price, hdpType, true, isLiveOutright, $M('ticket').getBetPageEnum('oddsDisplay'));
                if (isLiveOutright) {
                    option = 'or';
                } else {
                    option = 'or';
                }
                break;
            case "mp":
                $M('ticket').openMPTicket(oddsId, option, price, hdpType);
                break;
            default:
                $M('ticket').openTicket(oddsId, option, price, hdpType, false, isLiveOutright, $M('ticket').getBetPageEnum('oddsDisplay'), oddsSource);
                break;
        }
        if (oddsSource == $M('ticket').getBetPageEnum('favourite')) {
            var element = srcElement;
            while (element) {
                var id = element.id;
                if (id && id.indexOf('more-block-') > -1) {
                    oddsSource = $M('ticket').getBetPageEnum('more');
                    break;
                }
                element = element.parentNode;
            }
        }
        if (oddsSource == $M('ticket').getBetPageEnum('more')) {
            var childs = srcElement.childNodes;
            for (var i = 0; i <= childs.length; i++) {
                if (childs[i] && childs[i].className.indexOf('dummy-more-class') >= 0) {
                    _refNodes[oddsId + option] = childs[i];
                    _refDummyClassName[oddsId + option] = 'dummy-more-class';
                }
            }
        } else {
            while (srcElement) {
                var className = srcElement.className;
                if (className && className.indexOf('dummy-class') >= 0) {
                    _refNodes[oddsId + option] = srcElement;
                    _refDummyClassName[oddsId + option] = 'dummy-class';
                    break;
                }
                srcElement = srcElement.parentNode;
            }
        }
    }

    function _getOddsSource(ev) {
        var marketId = _oddsDisplayParam.getValue('market-page');
        if (marketId == 13) {
            return $M('ticket').getBetPageEnum('favourite');
        } else {
            while (ev) {
                var id = ev.id;
                if (id && id.indexOf('more-block-') > -1) {
                    return $M('ticket').getBetPageEnum('more');
                }
                ev = ev.parentNode;
            }
            var mktframe = _getMarketFrameId(false);
            switch (mktframe) {
                case 1:
                case 6:
                    return $M('ticket').getBetPageEnum('doublePage');
                case 2:
                case 7:
                    return $M('ticket').getBetPageEnum('singlePage');
                default:
                    return '';
            }
        }
        return '';
    }
    this.clearRef = function () {
        _selectedElements = {};
        _refNodes = {};
        _refDummyClassName = {};
        _firstOpen = false;
        $M('ticket').setDisabledGetOddsIdOption(false);
        return;
    }
    this.clearSelectedOdds = function () {
        if (!_firstOpen) {
            var elements = null;
            if (document.getElementsByClassName) {
                elements = document.getElementsByClassName('odds-selected');
            } else {
                elements = getElementsByClassName('odds-selected');
            }
            var selectedOddsElement = [];
            for (var i = 0; i < elements.length; i++) {
                selectedOddsElement.push(elements[i]);
            }
            for (var i = 0; i < selectedOddsElement.length; i++) {
                var node = selectedOddsElement[i];
                var className = node.className;
                var dummyClass = 'dummy-class';
                while (node) {
                    if (node.id) {
                        var ids = node.id.split(':');
                        if (ids[2] == 'price' || ids[2] == 'mpprice') {
                            dummyClass = 'dummy-more-class';
                            break;
                        }
                    }
                    node = node.parentNode;
                }
                selectedOddsElement[i].className = className.replace('odds-selected', dummyClass);
            }
            _firstOpen = true;
            $M('ticket').setDisabledGetOddsIdOption(true);
        }
        for (var selectedOddIdOption in _selectedElements) {
            var node = _refNodes[selectedOddIdOption];
            if (node) {
                var className = node.className;
                node.className = className.replace('odds-selected', _refDummyClassName[selectedOddIdOption]);
            }
        }
        _selectedElements = {};
        var force = true;
        var marketId = _self.getDisplaySetting('market-page');
        var oddIdOption = $M('ticket').getOddIdOption(force);
        if (oddIdOption && marketId != 9) {
            var dummyClassName = _refDummyClassName[oddIdOption];
            if (!dummyClassName) dummyClassName = 'dummy-class';
            var node = _refNodes[oddIdOption];
            if (!node) {
                var oddsOptions = $M('ticket').getOddIdOptions(force);
                var idString = oddsOptions.join(':');
                node = document.getElementById(idString);
                if (!node) {
                    var hdpOptions = ['', 0, 1, 2];
                    for (var i = 0; i < hdpOptions.length; i++) {
                        oddsOptions[oddsOptions.length - 1] = hdpOptions[i];
                        idString = oddsOptions.join(':');
                        node = document.getElementById(idString);
                        if (node) {
                            break;
                        }
                    }
                }
                if (node) {
                    var element = node;
                    while (element) {
                        var className = element.className;
                        if (className && className.indexOf('dummy-class') >= 0) {
                            _refNodes[oddIdOption] = element;
                            _refDummyClassName[oddIdOption] = 'dummy-class';
                            break;
                        }
                        element = element.parentNode;
                    }
                    var childs = node.childNodes;
                    for (var i = 0; i <= childs.length; i++) {
                        if (childs[i] && childs[i].className && childs[i].className.indexOf('dummy-more-class') >= 0) {
                            _refNodes[oddIdOption] = childs[i];
                            _refDummyClassName[oddIdOption] = 'dummy-more-class';
                        }
                    }
                }
                dummyClassName = _refDummyClassName[oddIdOption];
            }
            node = _refNodes[oddIdOption];
            if (node) {
                var className = node.className;
                className = className.replace('odds-change', '');
                node.className = className.replace(dummyClassName, 'odds-selected');
                _selectedElements[oddIdOption] = 1;
            } else { }
        }
        var oddsDictionary = $M('ticket').getOddsIdDictionary(force);
        if (oddsDictionary && marketId == 9) {
            for (var oddIdOption in oddsDictionary) {
                var dummyClassName = _refDummyClassName[oddIdOption];
                if (!dummyClassName) {
                    _refDummyClassName[oddIdOption] = 'dummy-class';
                }
                var node = _refNodes[oddIdOption];
                if (!node) {
                    var mpOptions = oddsDictionary[oddIdOption];
                    var idString = mpOptions.join(':');
                    node = document.getElementById(idString);
                    if (!node) {
                        var hdpOptions = ['', 0, 1, 2];
                        for (var i = 0; i < hdpOptions.length; i++) {
                            mpOptions[mpOptions.length - 1] = hdpOptions[i];
                            idString = mpOptions.join(':');
                            node = document.getElementById(idString);
                            if (node) {
                                break;
                            }
                        }
                    }
                    if (node) {
                        var element = node;
                        while (element) {
                            var className = element.className;
                            if (className && className.indexOf('dummy-class') >= 0) {
                                _refNodes[oddIdOption] = element;
                                _refDummyClassName[oddIdOption] = 'dummy-class';
                                break;
                            }
                            element = element.parentNode;
                        }
                        var childs = node.childNodes;
                        for (var i = 0; i <= childs.length; i++) {
                            if (childs[i] && childs[i].className && childs[i].className.indexOf('dummy-more-class') >= 0) {
                                _refNodes[oddIdOption] = childs[i];
                                _refDummyClassName[oddIdOption] = 'dummy-more-class';
                            }
                        }
                    }
                    dummyClassName = _refDummyClassName[oddIdOption];
                }
                node = _refNodes[oddIdOption];
                if (node) {
                    var className = node.className;
                    className = className.replace('odds-change', '');
                    node.className = className.replace(dummyClassName, 'odds-selected');
                    _selectedElements[oddIdOption] = 1;
                } else { }
            }
        }
    }
    this.refresh = function (clearAll) {
        if (_submodule && _submodule.refresh) {
            _submodule.refresh(clearAll);
        }
    };
    this.refreshLive = function (clearAll) {
        if (_submodule && _submodule.refreshLive) {
            _submodule.refreshLive(clearAll);
        }
    };
    this.refreshNonlive = function (clearAll) {
        if (_submodule && _submodule.refreshNonlive) {
            _submodule.refreshNonlive(clearAll);
        }
    };
    this.draw = function () {
        if (_submodule && _submodule.draw) {
            _submodule.draw();
        }
    };
    this.getDisplaySetting = function (key) {
        switch (key) {
            case 'display-in-local-time':
                return _displayInLocalTime;
            case 'daylight-type-period':
                return _daylightTypePeriod;
            case 'limited-rows':
                if (!_oddsDisplayInitialParams['limitedDisplayEnabled']) {
                    _limitedRows = Number.MAX_VALUE;
                }
                return _limitedRows;
            default:
                return _oddsDisplayParam.getValue(key);
        }
    };
    this.setDisplaySetting = function (key, value, position) {
        if (_setDisplaySetting(key, value, position)) {
            return true;
        }
        return false;
    };
    this.setDisplayParam = function (key, value) {
        if (_oddsDisplayParam.setValue(key, value)) {
            return true;
        }
        return false;
    };

    function _setDisplaySetting(key, value, position) {
        switch (key) {
            case 'display-in-local-time':
                _displayInLocalTime = value;
                if (_submodule && _submodule.draw) {
                    _submodule.draw();
                }
                break;
            case '1x2dc':
                _show1X2DC = value;
                _increaseToken();
                return _replaceSubmodule();
                break;
            case 'csft':
                _showFTCS = value;
                _increaseToken();
                return _replaceSubmodule();
                break;
            case 'sport-favourite':
                _oddsDisplayParam.setValue('sport', value);
                return _switchSportFavourite();
            case 'limited-rows':
                if (!_oddsDisplayInitialParams['limitedDisplayEnabled']) {
                    value = Number.MAX_VALUE;
                }
                _limitedRows = value;
                return;
            default:
                if (_oddsDisplayParam.getValue(key) != value) {
                    _oddsDisplayParam.setValue(key, value);
                    switch (key) {
                        case 'market-page':
                            CookieHelper.setValue('opened-market-id', value);
                            if ($M('global') && $M('global').redrawLeftColumn) {
                                window.scrollTo(0, 0);
                                $M('global').redrawLeftColumn();
                            }
                            _increaseToken();
                            return _replaceSubmodule();
                        case 'odds-mode':
                            _increaseToken();
                            return _replaceSubmodule();
                        case 'sport':
                            return _switchSport();
                        case 'daylight-type':
                            _increaseToken();
                            if (_submodule && _submodule.refresh) {
                                _submodule.refresh(true);
                                return true;
                            }
                            break;
                        case 'event-date':
                            _limitedRows = _additionalRows;
                            if (_submodule && _submodule.refresh) {
                                _submodule.refresh(true);
                                return true;
                            }
                            break;
                        case 'price-style':
                            _increaseToken();
                            CookieHelper.setValue('od-param-' + key, value);
                            if ($M('interested-event') && $M('interested-event').refresh) {
                                $M('interested-event').refresh(true);
                            }
                            if (_submodule && _submodule.refresh) {
                                _submodule.refresh(true);
                                return true;
                            }
                            break;
                        case 'sorting':
                            CookieHelper.setValue('od-param-' + key, value);
                            if (_submodule && _submodule.sort) {
                                _submodule.sort();
                                return true;
                            }
                            break;
                        case 'market-showing':
                            CookieHelper.setValue('od-param-' + key, value);
                            if ($M('more').isLiveMoreOpened()) {
                                $M('more').refresh(_getMarketFrameId(true));
                            }
                            if ($M('global') && $M('global').incGA && position) {
                                var category = value == 1 ? 'mainMarket' : 'allMarket';
                                $M('global').incGA(category, position);
                            }
                            if (_submodule && _submodule.draw) {
                                _submodule.draw();
                                return true;
                            }
                            break;
                    }
                }
        }
        return false;
    }

    function _increaseToken() {
        _oddsDisplayParam.setValue('token', _oddsDisplayParam.getValue('token') + 1);
    }

    function _switchSport() {
        _oddsDisplayParam.setValue('event-date', 0);
        var sportId = _oddsDisplayParam.getValue('sport');
        CookieHelper.setValue('opened-sport-id', sportId);
        if ($M('global') && $M('global').redrawLeftColumn) {
            window.scrollTo(0, 0);
            $M('global').redrawLeftColumn();
        }
        var marketPageId = _oddsDisplayParam.getValue('market-page');
        var newMarketPageId = $M('sport-market').getNewMarketPageId(sportId, marketPageId);
        if (!newMarketPageId && marketPageId == 13) {
            newMarketPageId = 13;
        }
        if (newMarketPageId != marketPageId) {
            _oddsDisplayParam.setValue('market-page', newMarketPageId);
            CookieHelper.setValue('opened-market-id', newMarketPageId);
            return _replaceSubmodule();
        } else if (_submodule && _submodule.refresh) {
            return _replaceSubmodule();
        }
        return false;
    }

    function _switchSportFavourite() {
        _oddsDisplayParam.setValue('market-page', 13);
        return _replaceSubmodule();
    }

    function _replaceSubmodule() {
        var newSubmodule = null;
        var marketPageId = _oddsDisplayParam.getValue('market-page');
        var sortingType = _oddsDisplayParam.getValue('sorting');
        var oddsDisplayInitialParams = _oddsDisplayInitialParams[marketPageId];
        if (!oddsDisplayInitialParams) {
            oddsDisplayInitialParams = 60;
        }
        _limitedRows = _additionalRows;
        var oddsMode = parseInt(_oddsDisplayParam.getValue('odds-mode'));
        switch (marketPageId) {
            case 1:
                switch (oddsMode) {
                    case 2:
                        newSubmodule = new __Module_TodaySingle(oddsDisplayInitialParams, sortingType);
                        break;
                    case 1:
                    default:
                        newSubmodule = new __Module_TodayDouble(oddsDisplayInitialParams, sortingType);
                        break;
                }
                break;
            case 2:
                switch (oddsMode) {
                    case 2:
                        newSubmodule = new __Module_EarlyMarketSingle(oddsDisplayInitialParams, sortingType);
                        break;
                    case 1:
                    default:
                        newSubmodule = new __Module_EarlyMarketDouble(oddsDisplayInitialParams, sortingType);
                        break;
                }
                break;
            case 3:
                switch (oddsMode) {
                    case 2:
                        newSubmodule = new __Module_LiveSingle(oddsDisplayInitialParams, sortingType);
                        break;
                    case 1:
                    default:
                        newSubmodule = new __Module_LiveDouble(oddsDisplayInitialParams, sortingType);
                        break;
                }
                break;
            case 4:
                newSubmodule = new __Module_OETG(oddsDisplayInitialParams, sortingType);
                break;
            case 5:
                switch (_showFTCS) {
                    case 2:
                        newSubmodule = new __Module_CS_FH(oddsDisplayInitialParams, sortingType);
                        break;
                    case 1:
                    default:
                        newSubmodule = new __Module_CS_FT(oddsDisplayInitialParams, sortingType);
                        break;
                }
                break;
            case 6:
                newSubmodule = new __Module_HTFT(oddsDisplayInitialParams, sortingType);
                break;
            case 7:
                switch (_show1X2DC) {
                    case 2:
                        newSubmodule = new __Module_FT_1X2(oddsDisplayInitialParams, sortingType);
                        break;
                    case 1:
                    default:
                        newSubmodule = new __Module_1X2_DC(oddsDisplayInitialParams, sortingType);
                        break;
                }
                break;
            case 8:
                newSubmodule = new __Module_FGLG(oddsDisplayInitialParams, sortingType);
                break;
            case 9:
                newSubmodule = new __Module_MixParlay(oddsDisplayInitialParams, sortingType);
                break;
            case 10:
                newSubmodule = new __Module_Outright(oddsDisplayInitialParams);
                break;
            case 13:
                switch (oddsMode) {
                    case 2:
                        newSubmodule = new __Module_FavouriteSingle(oddsDisplayInitialParams, sortingType);
                        break;
                    case 1:
                    default:
                        newSubmodule = new __Module_FavouriteDouble(oddsDisplayInitialParams, sortingType);
                        break;
                }
                break;
        }
        $M('more').clearMoreBlockInfo();
        if (newSubmodule != null) {
            if (_submodule != null && _submodule.dispose) {
                _submodule.dispose();
            }
            _submodule = newSubmodule;
            if (_submodule.initiate) {
                _submodule.initiate();
            }
            if (_submodule.refresh) {
                _submodule.refresh(true);
            }
            return true;
        }
        return false;
    }

    function _getMarketFrameId(isLive) {
        var oddsMode = _oddsDisplayParam.getValue('odds-mode');
        switch (_oddsDisplayParam.getValue('market-page')) {
            case 13:
            case 1:
                if (isLive) {
                    if (oddsMode == 2) {
                        return 2;
                    } else {
                        return 1;
                    }
                } else {
                    if (oddsMode == 2) {
                        return 7;
                    } else {
                        return 6;
                    }
                }
            case 2:
                if (oddsMode == 2) {
                    return 7;
                } else {
                    return 6;
                }
            case 3:
                if (oddsMode == 2) {
                    return 2;
                } else {
                    return 1;
                }
            case 4:
                if (isLive) {
                    return 23;
                } else {
                    return 11;
                }
            case 5:
                if (isLive) {
                    return 0;
                } else {
                    if (_showFTCS != 2) {
                        return 16;
                    } else {
                        return 17;
                    }
                }
            case 6:
                return 18;
            case 7:
                if (isLive) {
                    if (_show1X2DC != 2) {
                        return 12;
                    } else {
                        return 14;
                    }
                } else {
                    if (_show1X2DC != 2) {
                        return 13;
                    } else {
                        return 15;
                    }
                }
            case 8:
                return 19;
            case 9:
                return 20;
            case 10:
                if (isLive) {
                    return 21;
                } else {
                    return 22;
                }
            default:
                return 0;
        }
    }
}
